package com.netty.timeold;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter {

	private final ByteBuf firstMessage;

	String name = "";
	int result = 0;

	public TimeClientHandler(String name) {
		this.name = name;
		String str = "QUERY TIME ORDER";
		byte[] req = str.getBytes(StandardCharsets.UTF_8);
		firstMessage = Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
		System.out.println("------------------");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		System.out.println("---ctx.close()");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// ctx.writeAndFlush(firstMessage);
		String str = "QUERY TIME ORDER " + name;
		ctx.writeAndFlush(Unpooled.copiedBuffer(str.getBytes(StandardCharsets.UTF_8)));
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(ctx);
		String body = (String) msg;
		System.out.println("Now is :" + body);
	}

}
